package com.example.calendarapp;

import java.util.ArrayList;
import java.util.List;

import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

/**
 * Fragment for displaying categories in a simple list view
 * @author nathan
 *
 */

public class CategoryFragment extends Fragment implements OnItemClickListener{

	private ListView lv;
	private EventsDataSource data;
	private List<EventCategory> cats;
	private Button addBtn;
	
	/**
	 * onCreate opens the database object and loads the categories
	 * 
	 * @param Bundle savedInstanceState
	 * 
	 */
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	    	super.onCreate(savedInstanceState);
    	    	data = EventsDataSource.getInstance(getActivity());
    	    	data.createDatabase();
    	    	data.open();
    	    	cats = data.getCategories();
    }	   
	
    /**
     * onCreateView inflates the view and sets the list adaper and onclick methods
     * 
     * @param LayoutInflater
     * @param ViewGroup
     * @param Bundle
     * 
     * @return View v
     */
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.categoryfragment, null);
		
		lv = (ListView) v.findViewById(R.id.catList);
		List<String> catList = new ArrayList<String>();
		catList = data.getCategoriesStrings();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, catList);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(this);
		
		addBtn = (Button) v.findViewById(R.id.addCatBtn);
		addBtn.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v) {
				FragmentManager fm = getFragmentManager();
				FragmentTransaction ft = fm.beginTransaction();
				CategoryEditFragment f = new CategoryEditFragment();
				ft.replace(R.id.frag, f);
				ft.commit();						
			}
			
			
		});
		
		
		return v;
	}
	
    /**
     * onItemClick starts new Category Edit Fragment
     * 
     * @param AdapterView<?>
     * @param View
     * @param int
     * @param int
     * 
     */
    
    @Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		Bundle bundle = new Bundle();
		bundle.putInt("id", arg2);
		FragmentManager fm = getFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		CategoryEditFragment f = new CategoryEditFragment();
		f.setArguments(bundle);
		ft.replace(R.id.frag, f);
		ft.commit();		
	}
    
}
